package com.feituan.core.service.impl;


import com.feituan.core.persistence.mapper.UserCouponMapper;
import com.feituan.core.persistence.service.ICouponService;
import com.feituan.core.pojo.entity.*;
import com.feituan.core.service.ITypeCouponsService;
import com.feituan.core.service.IVipFissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class VipFissionServiceImpl implements IVipFissionService {

    @Autowired
    private UserCouponMapper userCouponMapper;

    @Autowired
    private ITypeCouponsService typeCouponsService;

    @Autowired
    private ICouponService couponService;

    @Override
    public boolean saveVipFission(VipFission vipFission) {
        TypeCoupons typeCoupons = typeCouponsService.selectByType(vipFission.getType());
        try {
            for (Coupons coupon : typeCoupons.getCoupons()) {
                Long id = coupon.getCouponId();
                Coupon info = couponService.selectById(id);
                if (info != null) {
                    UserCoupon userCoupon = new UserCoupon();
                    userCoupon.setCreateTime(new Date());
                    userCoupon.setUserId(vipFission.getUserId());
                    userCoupon.setCouponStatus(0);
                    userCoupon.setCouponId(id);
                    userCouponMapper.insert(userCoupon);
                    UserCoupon newUserCoupon = new UserCoupon();
                    newUserCoupon.setCreateTime(new Date());
                    newUserCoupon.setUserId(vipFission.getNewUserId());
                    newUserCoupon.setCouponStatus(0);
                    newUserCoupon.setCouponId(id);
                    userCouponMapper.insert(newUserCoupon);
                }
            }
        } catch (Exception e) {
            throw new IllegalStateException("会员裂变失败");
        }
        return true;
    }
}
